/*
 * Copyright 2007-2009 Thomas Krause (thomas@berlin-reloaded.de)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gidoo.cms.extra.simplemenu;

import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.gidoo.cms.GidooCMS;
import org.gidoo.cms.helper.Tools;
import org.gidoo.cms.jcr.JcrHelper;
import org.gidoo.cms.login.GidooCMSSession;

/**
 * A simple tree menu which allows you to control which nodes are apearing.
 * It uses &lt;ul&gt; and &lt;li&gt; elements.
 * @author <a href="mailto:thomas@berlin-reloaded.de">Thomas Krause</a>
 * 
 * @see #shouldAddThisNode(javax.jcr.Node) 
 */
public class SimpleTreeMenu extends Panel
{

  /**
   * Constructor.
   * 
   * @param id The wicket id.
   * @param parentNode The parent node. Use null if you want all sections as parent nodes.
   * @param currentPagePath The path to the current visited page (without leading "/")
   */
  public SimpleTreeMenu(String id, Node parentNode, final String currentPagePath)
  {
    super(id);

    List<String> children = new LinkedList<String>();
    
    try
    {
      NodeIterator it = null;
      if(parentNode == null)
      {
        Node root = ((GidooCMSSession) getSession()).getJcrRootNode();
        it = root.getNode("sections").getNodes();
      }
      else
      {
        it = parentNode.getNodes();
      }

      while(it.hasNext())
      {
        Node n = it.nextNode();
        
        if(shouldAddThisNode(n))
        {
          children.add(n.getPath().substring(1));
        }
      }
    }
    catch(RepositoryException ex)
    {
      Logger.getLogger(SimpleTreeMenu.class.getName()).log(Level.SEVERE, null, ex);
    }


    ListView<String> lsvMenu = new ListView<String>("lsvMenu", children)
    {

      @Override
      protected void populateItem(ListItem<String> item)
      {
        try
        {

          if(item == null)
          {
            throw new NullPointerException();
          }

          Node root = ((GidooCMSSession) getSession()).getJcrRootNode();
          if(root.hasNode(item.getModelObject()))
          {
            // fill list with single items
            Node n = root.getNode(item.getModelObject());

            WebMarkupContainer row = new WebMarkupContainer("row");

            String url = Tools.getRootURLForWebapp((GidooCMS) getApplication())
              + JcrHelper.getPartialURLForNode(n)
              + "/";

            ExternalLink link = new ExternalLink("link", url);
            
            Label label = new Label("label", new Model(n.getProperty("cms:title").getString()));
            link.add(label);
            label.setRenderBodyOnly(true);

            // disable if current page
            if(currentPagePath.equals(n.getPath().substring(1)))
            {
              link.setEnabled(false);
            }

            row.add(link);
            item.add(row);
            item.setRenderBodyOnly(true);

            // recursive adding
            NodeIterator itChildren = n.getNodes();
            boolean hasPublishedChildren = false;
            
            while(!hasPublishedChildren && itChildren.hasNext())
            {
              Node c = itChildren.nextNode();
              if(shouldAddThisNode(c))
              {
                hasPublishedChildren = true;
              }
            }
            
            if(hasPublishedChildren)
            {
              SimpleTreeMenu nestedList = new SimpleTreeMenu("nestedList", n, currentPagePath);
              nestedList.setRenderBodyOnly(true);
              item.add(nestedList);
            }
            else
            {
              // no children
              WebMarkupContainer nestedList = new WebMarkupContainer("nestedList");
              nestedList.setVisible(false);
              item.add(nestedList);
            }
          }
        }
        catch(RepositoryException ex)
        {
          Logger.getLogger(SimpleTreeMenu.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
      
    };

    add(lsvMenu);

  }
  
  
  /**
   * Override this in order to control which pages are added and which not.
   * @param n The node to check.
   * @return True if should be added. By default it calls 
   *          {@link org.gidoo.cms.jcr.JcrHelper#isPublished(javax.jcr.Node)}
   */
  public boolean shouldAddThisNode(Node n)
  {
    return JcrHelper.isPublished(n);
  }
   
  
}
